# 用不蓝图
from flask import Blueprint, request, render_template, redirect

from apps.user.model import User

use_bp = Blueprint('users', __name__)

users = list()


@use_bp.route('/', endpoint='show')
def welcome():
    return render_template('users/show.html', users=users)
    # return '欢迎首页'


@use_bp.route('/login', methods=['GET', 'POST'])
def login():
    return '注册'


@use_bp.route('/logout')
def logout():
    return '退出'


@use_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        # get password and username
        username = request.form.get('username')
        password = request.form.get('password')
        repassword = request.form.get("repassword")
        phone = request.form.get('phone')
        if password == repassword:
            for user in users:
                if user.username == username:
                    return render_template('users/register.html', msg='当前用户已经存在')
            user = User(username, password, phone)
            users.append(user)
            return redirect('/')
    return render_template('users/register.html')


# 删除数据
@use_bp.route('/del')
def use_del():
    for user in users:
        if user.username == request.args.get('username'):
            users.remove(user)
            return '删除成功'
    return '删除失败'


# 修改用户信息
@use_bp.route('/update', methods=['POST', 'GET'], endpoint='update')
def use_update():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        phone = request.form.get('phone')
        for user in users:
            if user.username == username:
                user.password = password
                user.phone = phone
        return redirect('/')
    else:
        username = request.args.get('username')
        for user in users:
            if user.username == username:
                return render_template('users/update.html', user=user)
            else:
                return '没有该用户'
